<?php
class Session
{
    var $db = '';
    
    public function __construct($db)
    {
        $this->db = $db;
    }
    
    public function check()
    {
        if(isset($_SESSION['session_id']) && isset($_SESSION['token']))
        {
            //$Sql = $GLOBALS['db']->query("SELECT id FROM immo_session WHERE id = '". $_SESSION['session_id'] ."' AND token = '". $_SESSION['token'] ."' AND ip = '". base64_encode($_SERVER['REMOTE_ADDR']) ."'");
            //if($GLOBALS['db']->sql_nbresultat($Sql) == 1)
            if($GLOBALS['db']->sql_nbresultat(null, "SELECT COUNT(id) FROM immo_session WHERE id = '". $_SESSION['session_id'] ."' AND token = '". $_SESSION['token'] ."' AND ip = '". base64_encode($_SERVER['REMOTE_ADDR']) ."'") == 1)
            {
                $QueryArray = array(
                'last_used' => time(),
                'page'  =>  get_currentpage());
                
                $GLOBALS['db']->execute(CreateQueryUpdate($QueryArray, 'immo_session', " id = '". $_SESSION['session_id'] ."' AND token = '". $_SESSION['token'] ."' AND ip = '". base64_encode($_SERVER['REMOTE_ADDR']) ."'"));

                return true;
            }
            else
            {
                $this->delete($_SESSION['session_id']);
                session_destroy();
				return false;
            }
        }
		else
			return false;                    
    }
    
    /**
     * @desc Permet de creer la session utilisateur
     * @return void
     * */
    public function create()
    {
       // Si deja session on la supprime 
       if(isset($_SESSION['session_id'])) 
        $this->delete($_SESSION['session_id']); 
        
       $_SESSION['token'] = md5(uniqid(rand(), true));                              // Creation d un token
       $_SESSION['session_id'] = md5(uniqid(rand(), true));                         // Creation de l id de session 
       $this->insert_new_session($_SESSION['token'], $_SESSION['session_id']);      // Enregistrement de la session  
    }
    
    private function insert_new_session($token, $session_id)
    {
        $QueryArray = array(
        'id'    =>  $session_id,
        'token' =>  $token,
        'date_create'   =>  time(),
        'last_used' =>  time(),
        'ip'    =>  base64_encode($_SERVER['REMOTE_ADDR']),
        'page'  =>  get_currentpage());
        
        $GLOBALS['db']->execute(CreateQueryInsert($QueryArray, 'immo_session'));   
    }
    
    private function delete($session_id)
    {
        $GLOBALS['db']->execute("DELETE FROM immo_session WHERE id = '". $session_id ."'");   
    }

	
	public function delete_session_time()
	{
		$GLOBALS['db']->execute("DELETE FROM immo_session WHERE last_used < '". time() . " - 1800 '");
	}
    
}